package com.easy.activiti;

import com.easy.activiti.ext.IActivitiCoreService;
import com.easy.activiti.controller.UserController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Optional;

/**
 * @author zhouchuang
 * 2024-11-02 18:21:51
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(LoginInterceptor.class);

    @Autowired
    private IActivitiCoreService activitiCoreService;

    @Autowired
    private UserController userController;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 这里以session为例，检查session中是否有用户登录信息
//        log.error("getRequestedSessionId="+request.getRequestedSessionId());
        if(!isLoggedIn()){
            log.error("===========没有登陆，自动登陆===========");
            IActivitiCoreService.AuthConfigServer.User user = activitiCoreService.authConfigServer().loginUser();
            if (user == null) {
                // 用户未登录，返回401（未授权）或可以重定向到登录页面
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "用户未登录");
                return false; // 终止请求
            }else{
                //提前获取业务系统的JESSIONID
                Cookie[] cookies = request.getCookies();
                Optional<Cookie> JSESSIONID = Arrays.stream(cookies).filter(t -> "JSESSIONID".equals(t.getName())).findFirst();
                String oldJessionId = null;
                if(JSESSIONID.isPresent()){
                    oldJessionId = JSESSIONID.get().getValue();
                }
                userController.logInAs(user);
                if (!response.isCommitted()) {
                    Cookie bakCookie = new Cookie("BS_JSESSIONID", oldJessionId);
                    bakCookie.setPath("/"); // 设置路径为根路径
                    bakCookie.setHttpOnly(true); // 设置HttpOnly属性
                    response.addCookie(bakCookie);
                }
            }
        }
        return true; // 继续处理请求
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求完全完成后进行调用，也就是在DispatcherServlet渲染了对应的视图之后执行
    }
    public  boolean isLoggedIn() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        boolean isLogin =  authentication != null && authentication.isAuthenticated()
                && !(authentication instanceof AnonymousAuthenticationToken);
        if(isLogin){//如果已经登陆了，判断下线程变量中是否等于用户信息
            IActivitiCoreService.AuthConfigServer.User user = activitiCoreService.authConfigServer().loginUser();
            if(user==null || !user.getUserName().equals(authentication.getName())){
                isLogin = false;
            }
        }
        return isLogin;
    }
}
